import { SingleDownloadTask } from "./SingleDownloadTask";
import { DownloadCenter } from "./DownloadCenter";
import { FileDownloader } from "./FileDownloader";
import { FileUtil } from "../../utils/FileUtil";
import { SqlLibUser } from "../sqlite/service/SqlLibUser";
import { SqlLib } from "../sqlite/SqlLib";

const POLYV_VIDEO = "PolyvVideo";

export class CloudResDownloader {

    constructor() {
        this.fileDownloader = null;
        this.isPausing = false; //是否暂停状态
    }

    /**
     * 获取下载器单例的对象
     * @return {CloudResDownloader}
     */
    static getInstance () {
        if (!this.instance) {
            this.instance = new CloudResDownloader();
            return this.instance;
        } else {
            return this.instance;
        }
    }

    /**
     * 下载单个云资源
     * @param request 资源请求的类库
     * @param item 资源详情
     */
    downloadOneResource (request, item, progressCallback, successCallback) {
        let itemBsr = {
            metaId: item.meta_id,
            metaType: DownloadCenter.getInstance().resTypeToEnName(item.res_type)
        }
        let _this = this;
        request.getResourceInfoByResIds({
            metaParamDTOS: itemBsr
        }).then(response => {
            let bsrResources = response.returnValue.resources[itemBsr.metaId];
            let downloadParam = {
                TaskId: itemBsr.metaId,
                FileType: itemBsr.metaType,
                FileName: itemBsr.metaType === "PolyvVideo" ? itemBsr.metaId : itemBsr.metaId + ".zip",
                Url: item.zip_url ? item.zip_url : "",
                Bsr: JSON.stringify(bsrResources)
            }
            let singleTask = new SingleDownloadTask(downloadParam, function () {
                if (singleTask.downloadParam.FileType === POLYV_VIDEO) {
                    _this.fileDownloader = singleTask.fileDownloader.fileDownloader
                } else {
                    _this.fileDownloader = singleTask.fileDownloader;
                }
                console.log('_this.fileDownloader----------',_this.fileDownloader);
                _this.isPausing = false;//置为不暂停状态
                _this.fileDownloader.downloadFile(null, function (recievBytes, speed) {
                    if (progressCallback) {
                        progressCallback(parseInt((recievBytes * 100 / _this.fileDownloader.totalSize).toFixed()), speed);
                    }
                }, function () {
                    if (!_this.isPausing) {//如果是暂停状态，不给成功回调
                        //下载成功埋点
                        let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                        DownloadCenter.getInstance().recordUserDownloadInfo({
                            resourceType: singleTask.downloadParam.FileType,
                            resourceId: singleTask.downloaderId,
                            eduLevelId: user.eduLevelId,
                            packageSize: _this.fileDownloader.totalSize
                        });

                        const path = require("path");
                        if (_this.fileDownloader.sourceName.endsWith(".zip")) {
                            if (itemBsr.metaType === POLYV_VIDEO) {
                                FileUtil.unzipFileAndRename(_this.fileDownloader.sourceName, false, false, function () {
                                    // console.log('111111111111',itemBsr.metaType,itemBsr.metaId);
                                    let downloader = new FileDownloader(item.thumb, path.resolve(window.$DATADIR, "resc", itemBsr.metaType, itemBsr.metaId, "thumb"));
                                    downloader.downloadFile();
                                    if (successCallback) {
                                        successCallback(downloadParam.Bsr);
                                    }
                                    _this.fileDownloader = null;
                                }, function () {
                                    console.log("downloadOneResource :: 解压失败")
                                    _this.fileDownloader = null;
                                });
                            } else {
                                FileUtil.unzipFileAndRename(_this.fileDownloader.sourceName, true, true, function () {
                                    // console.log('2222222222',itemBsr.metaType,itemBsr.metaId);
                                    let downloader = new FileDownloader(item.thumb, path.resolve(window.$DATADIR, "resc", itemBsr.metaType, itemBsr.metaId, "thumb"));
                                    downloader.downloadFile();
                                    if (successCallback) {
                                        successCallback(downloadParam.Bsr);
                                    }
                                    _this.fileDownloader = null;
                                }, function () {
                                    console.log("downloadOneResource :: 解压失败")
                                    _this.fileDownloader = null;
                                });
                            }
                        }
                    }
                }, null);
            })
        })
    }

    /**
     * 下载课时的单个资源
     * @param downloadParam
     * @param progressCallback
     * @param successCallback
     * @param errorCallback
     */
    downloadLessonResource (downloadParam, progressCallback, successCallback, errorCallback) {
        let _this = this;
        const path = require("path");
        if (downloadParam.FileType === 'courseware') {
            let fileName = path.resolve(window.$DATADIR, "resc", "courseware", downloadParam.TaskId + ".pptx");
            FileDownloader.getTotalSize(downloadParam.Url, function (totalSize) {
                if (totalSize !== 0) {
                    let downloader = new FileDownloader(downloadParam.Url, fileName);
                    downloader.downloadFile(null, function (recievBytes, speed) {
                        if (progressCallback) {
                            progressCallback(parseInt((recievBytes * 100 / totalSize).toFixed()), speed);
                        }
                    }, successCallback, errorCallback);
                } else {
                    if (errorCallback) {
                        errorCallback();
                    }
                }
            });
        } else {
            let singleTask = new SingleDownloadTask(downloadParam, function () {
                if (singleTask.downloadParam.FileType === POLYV_VIDEO) {
                    _this.fileDownloader = singleTask.fileDownloader.fileDownloader
                } else {
                    _this.fileDownloader = singleTask.fileDownloader;
                }
                _this.fileDownloader.downloadFile(null, function (recievBytes, speed) {
                    if (progressCallback) {
                        progressCallback(parseInt((recievBytes * 100 / _this.fileDownloader.totalSize).toFixed()), speed);
                    }
                }, function () {
                    //下载成功埋点
                    let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                    DownloadCenter.getInstance().recordUserDownloadInfo({
                        resourceType: singleTask.downloadParam.FileType,
                        resourceId: singleTask.downloaderId,
                        eduLevelId: user.eduLevelId,
                        packageSize: _this.fileDownloader.totalSize
                    });

                    if (_this.fileDownloader.sourceName.endsWith(".zip")) {
                        if (singleTask.downloadParam.FileType === POLYV_VIDEO ) {
                            FileUtil.unzipFileAndRename(_this.fileDownloader.sourceName, false, false, function () {
                                if (successCallback) {
                                    successCallback();
                                }
                                _this.fileDownloader = null;
                            }, function () {
                                if (errorCallback) {
                                    errorCallback();
                                }
                                console.log("downloadLessonResource :: 解压失败");
                                _this.fileDownloader = null
                            });
                        } else {
                            FileUtil.unzipFileAndRename(_this.fileDownloader.sourceName, true, true, function () {
                                if (successCallback) {
                                    successCallback();
                                }
                                _this.fileDownloader = null;
                            }, function () {
                                if (errorCallback) {
                                    errorCallback();
                                }
                                console.log("downloadLessonResource :: 解压失败");
                                _this.fileDownloader = null
                            });
                        }
                    }
                }, errorCallback);
            })
        }
    }

    isDownloading () {
        if (this.fileDownloader) {
            this.isPausing = true;
            return true;
        } else {
            return false;
        }
    }

    pauseDownload () {
        if (this.fileDownloader) {
            this.fileDownloader.pauseDownload()
        }
    }
}
